<template>
  <div>
    <!-- 饼状图 -->
    <div id="pieChart" style="height: 400px;"></div>

    <!-- 搜索框及按钮 -->
    <el-input placeholder="请输入姓名" v-model="Sno" id="text"></el-input>
    <el-button @click="search" :icon="Search">搜索</el-button>

    <!-- 导出按钮 -->
    <el-button @click="exportToCSV" type="primary">导出成绩</el-button>

    <!-- 刷新按钮 -->
    <el-button @click="refreshData" type="warning">重置</el-button> <!-- 刷新按钮 -->
    <!-- 提示信息 -->
    <p v-if="!editable" style="color: red;">当前成绩录入功能已关闭，请联系管理员。</p>
  </div>

  <div style="padding: 20px;">
    <el-table class="currentTable" :data="students" :header-cell-style="{ background: '#f6f9fa'}">
      <el-table-column prop="sno" label="学号"></el-table-column>
      <el-table-column prop="sname" label="姓名"></el-table-column>
      <el-table-column prop="classid" label="班级"></el-table-column>
      <el-table-column prop="score" label="成绩">
        <template #default="scope">
          <el-input
              v-if="scope.row.editing && editable"
              v-model="scope.row.score"
              @blur="handleEdit(scope.row)"
          ></el-input>
          <span v-else>{{ scope.row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180">
        <template #default="{ row }">
          <el-button
              type="primary"
              :icon="Edit"
              @click="toggleEdit(row)"
              :disabled="!editable"
          >
            {{ row.editing ? '确定' : '编辑' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import {ref, onMounted, watch} from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import * as echarts from "echarts";
import { Edit, Search } from "@element-plus/icons-vue";

const route = useRoute();
const id = route.query.cno;
let Sno = ref('');
const students = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const editable = ref(false);

// 存储所有数据
let allStudents = ref([]);
let loading = ref(false);
let filteredStudents = ref([]); // 用于存储过滤后的学生数据

// 确保页面加载时自动刷新数据
onMounted(() => {
  getScoreEntryStatus();
  getAllData(); // 自动刷新获取数据
  setInterval(getScoreEntryStatus, 1000);
});

const getScoreEntryStatus = () => {
  axios.get("http://localhost:8080/scoreEntryStatus").then(res => {
    editable.value = res.data.enabled;
  });
};

// 一次性获取所有数据
const getAllData = () => {
  loading.value = true;
  axios
      .get('http://localhost:8080/getStudentScoreByCno', {
        params: {
          page: 1,
          size: -1, // 特殊值表示获取所有数据（需后端支持）
          cno: route.query.cno,
          sno: Sno.value,
        },
      })
      .then((response) => {
        allStudents.value = response.data.records; // 保存所有数据
        total.value = allStudents.value.length; // 更新总记录数
        filteredStudents.value = [...allStudents.value]; // 默认加载所有数据
        drawPieChart(); // 绘制饼状图
        getPageData(); // 初始化分页数据
        loading.value = false;
      })
      .catch((error) => {
        console.error(error);
        loading.value = false;
      });
};

// 监听路由参数变化
watch(
    () => route.query.cno,
    (newCno) => {
      if (newCno) {
        getAllData(); // 当 cno 变化时重新获取数据
      }
    },
    { immediate: true } // 立即执行一次
);


// 获取当前分页数据
const getPageData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = currentPage.value * pageSize.value;
  students.value = filteredStudents.value.slice(start, end); // 修改为从过滤后的数据中获取分页内容
};

// 绘制饼状图
const drawPieChart = () => {
  const scores = allStudents.value.map((student) => student.score);

  const scoreDistribution = {
    不合格: 0,
    一般: 0,
    良好: 0,
    优秀: 0,
  };

  scores.forEach((score) => {
    if (score < 60) scoreDistribution.不合格 += 1;
    else if (score < 76) scoreDistribution.一般 += 1;
    else if (score < 85) scoreDistribution.良好 += 1;
    else scoreDistribution.优秀 += 1;
  });

  const chartData = [
    { value: scoreDistribution.不合格, name: '不合格' },
    { value: scoreDistribution.一般, name: '一般' },
    { value: scoreDistribution.良好, name: '良好' },
    { value: scoreDistribution.优秀, name: '优秀' },
  ];

  const chart = echarts.init(document.getElementById('pieChart'));
  const option = {
    title: {
      text: '成绩分布情况',
      subtext: '成绩区间统计',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    series: [
      {
        name: '成绩分布',
        type: 'pie',
        radius: '50%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };

  chart.setOption(option);

  // 添加点击事件监听器
  chart.on('click', (params) => {
    // 点击某个部分时，过滤对应类别的学生
    filterStudentsByScoreCategory(params.name);
  });
};

// 根据成绩类别过滤学生数据
const filterStudentsByScoreCategory = (category) => {
  filteredStudents.value = allStudents.value.filter((student) => {
    if (category === '不合格') return student.score < 60;
    if (category === '一般') return student.score >= 60 && student.score < 76;
    if (category === '良好') return student.score >= 76 && student.score < 85;
    if (category === '优秀') return student.score >= 85;
    return false;
  });
  total.value = filteredStudents.value.length; // 更新分页的总记录数
  getPageData(); // 更新分页内容
};

// 切换编辑状态
const toggleEdit = (row) => {
  if (row.editing) {
    handleEdit(row);
  } else {
    row.editing = true;
  }
};

// 编辑后提交
const handleEdit = (row) => {
  row.editing = false;
  axios.put(`http://localhost:8080/updateScore?cno=${id}&sno=${row.sno}&score=${row.score}`).then(() => { drawPieChart(); })
      .catch(error => {
        window.alert(error);
      });
};

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getPageData();
};

const handleSizeChange = (pagesize) => {
  pageSize.value = pagesize;
  getPageData();
};

// 搜索
const search = () => {
  getAllData();
};

// 导出为 CSV
const exportToCSV = () => {
  const headers = ['学号', '姓名', '班级', '成绩'];
  const rows = allStudents.value.map((student) => [
    student.sno,
    student.sname,
    student.classid,
    student.score,
  ]);
  const csvContent = [headers, ...rows]
      .map((row) => row.join(','))
      .join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = '成绩数据.csv';
  link.click();
};

// 刷新按钮功能
const refreshData = () => {
  filteredStudents.value = [...allStudents.value]; // 恢复为所有学生数据
  total.value = filteredStudents.value.length; // 更新总记录数
  currentPage.value = 1; // 重置为第一页
  getPageData(); // 更新分页
};
</script>

<style scoped>
#pieChart {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}
</style>
